/**
 * 您可以将常用的方法、或系统 API，统一封装，暴露全局，以便各页面、组件调用，而无需 require / import.
 */
const prompt = require('@system.prompt')

/**
 * 拼接 url 和参数
 */
function queryString(url, query) {
  let str = []
  for (let key in query) {
    str.push(key + '=' + query[key])
  }
  let paramStr = str.join('&')
  return paramStr ? `${url}?${paramStr}` : url
}

function showToast(message = '', duration = 0) {
  if (!message) return
  prompt.showToast({
    message: message,
    duration
  })
}

/**
 * 格式化时间
 * @returns string
 */
function formatDateTime(timesnap) {
  const dateTime = new Date(timesnap);
  const year = dateTime.getFullYear();
  const month = dateTime.getMonth() + 1;
  const date = dateTime.getDate(); 
  const hours = `${dateTime.getHours()}`; //.padStart(2, "0"); 
  const minutes = `${dateTime.getMinutes()}`; //.padStart(2, "0");
  const seconds = `${dateTime.getSeconds()}`; //.padStart(2, "0");

  return `${year}年${month}月${date}日 ${hours}:${minutes}:${seconds}`;
}

/**
 * 判断当前是否为浏览器平台
 * @returns boolean
 */
const isBrowser = () => {
  return typeof window !== 'undefined';
}

/** 生成统一错误对象 */
const newError = (code, message) => ({
  err_code: code,
  err_message: message
});

function awaitWrapType(promise) {
  return promise
    .then((data) => [undefined, data])
    .catch((err) => [err, undefined]);
}

export default {
  showToast,
  queryString,
  formatDateTime,
  isBrowser,
  newError,
  awaitWrapType
}
